package com.iteaj.iot.client.protocol;

import com.iteaj.iot.client.IotClientBootstrap;
import com.iteaj.iot.client.SocketClient;
import com.iteaj.iot.client.TcpSocketClient;
import com.iteaj.network.ProtocolHandle;
import com.iteaj.network.client.ClientMessage;
import com.iteaj.network.client.ClientProtocol;
import com.iteaj.network.client.ClientProtocolHandle;
import com.iteaj.network.protocol.socket.AbstractSocketProtocol;
import io.netty.channel.socket.DatagramPacket;

/**
 * create time: 2021/8/6
 *
 * @author iteaj
 * @since 1.0
 */
public abstract class ClientSocketProtocol<C extends ClientMessage> extends AbstractSocketProtocol<C> implements ClientProtocol<C> {

    /**
     * udp协议报文
     */
    private DatagramPacket packet;

    private ClientProtocolHandle defaultProtocolHandle; // 默认协议处理器

    @Override
    public C requestMessage() {
        return super.requestMessage();
    }

    @Override
    public C responseMessage() {
        return super.responseMessage();
    }

    /**
     * 返回客户端
     * @return
     */
    public SocketClient getIotClient() {
        return IotClientBootstrap.getClient(requestMessage.getClass());
    }

    /**
     * 是否是tcp客户端
     * @return
     */
    public boolean isTcpClient() {
        SocketClient iotClient = getIotClient();
        if(iotClient instanceof TcpSocketClient) {
            return true;
        } else {
            return false;
        }
    }

    protected String getMessageId() {
        ClientMessage message = requestMessage();
        return message.getMessageId();
    }

    public ClientProtocolHandle getDefaultProtocolHandle() {
        if(defaultProtocolHandle == null) {
            defaultProtocolHandle = (ClientProtocolHandle) IotClientBootstrap
                    .businessFactory.getProtocolHandle(getClass());
        }

        return defaultProtocolHandle;
    }

    public DatagramPacket getPacket() {
        return packet;
    }

    public void setPacket(DatagramPacket packet) {
        this.packet = packet;
    }
}
